package com.aoxon.cargo.activity;

import java.io.FileNotFoundException;
import java.io.IOException;

import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aoxon.cargo.R;
import com.aoxon.cargo.bean.GsonBean;
import com.aoxon.cargo.bean.Index;
import com.aoxon.cargo.bean.Supplier;
import com.aoxon.cargo.cache.SupCache;
import com.aoxon.cargo.cache.keyCache;
import com.aoxon.cargo.component.SupplierInfoShow;
import com.aoxon.cargo.loader.NormalDataLoader;
import com.aoxon.cargo.service.MyServiceFactory;
import com.aoxon.cargo.service.SupplierIndexService;
import com.aoxon.cargo.shared.SupIndexShared;
import com.aoxon.cargo.state.DataState;
import com.aoxon.cargo.state.MyStateUtil;
import com.aoxon.cargo.util.CheckStateUtil;
import com.aoxon.cargo.util.DataUtil;
import com.aoxon.cargo.util.EnvironmentUtil;
import com.aoxon.cargo.util.ToastUtil;

/**
 * 供应商首页
 * 
 * @author ZZJ
 * 
 */
public class SupIndexActivity extends BaseActivity implements
		NormalDataLoader.OnLoadDataListener {

	private ImageView ivReturnButton;
	private ImageView ivSettingButton;

	private TextView tvTitle;
	private TextView tvGoodsMessage;
	private TextView tvCertificationMessage;
	private TextView tvSystemMessage;
	private TextView tvQuickAddButton;

	private RelativeLayout rlGoodsManagement;
	private RelativeLayout rlApplyCertification;
	private RelativeLayout rlSystemMessages;

	private GsonBean gsonBean;

	private SupplierInfoShow supplierInfoShow;

	private NormalDataLoader normalDataLoader = new NormalDataLoader(this);

	private SupplierIndexService supplierIndexService = (SupplierIndexService) MyServiceFactory
			.getInstance(MyServiceFactory.SUPPLIER_INDEX);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setup();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		beginShow();
		super.onResume();
	}

	private void setup() {
		setContentView(R.layout.sup_index);

		// the title setting

		ivReturnButton = (ImageView) findViewById(R.id.ivPublicTitleReturn);
		ivSettingButton = (ImageView) findViewById(R.id.ivPublicTitleOther);
		tvTitle = (TextView) findViewById(R.id.tvPublicTiTle);
		tvGoodsMessage = (TextView) findViewById(R.id.tvSupIndexGoodsMessage);
		tvCertificationMessage = (TextView) findViewById(R.id.tvSupIndexApplyCertificationMessage);
		tvSystemMessage = (TextView) findViewById(R.id.tvSupIndexSystemMessages);
		tvQuickAddButton = (TextView) findViewById(R.id.tvSupIndexQuickAddButton);

		rlGoodsManagement = (RelativeLayout) findViewById(R.id.rlSupIndexGoodsManagement);
		rlApplyCertification = (RelativeLayout) findViewById(R.id.rlSupIndexApplyCertification);
		rlSystemMessages = (RelativeLayout) findViewById(R.id.rlSupIndexSystemMessages);

		supplierInfoShow = new SupplierInfoShow(this);

		normalDataLoader.setOnloadDataListener(this);

		tvTitle.setText("拿货助手供应商");
		ivSettingButton.setImageResource(R.drawable.button_setting);

		ivReturnButton.setOnClickListener(myClickListener);
		ivSettingButton.setOnClickListener(myClickListener);
		tvQuickAddButton.setOnClickListener(myClickListener);
		rlGoodsManagement.setOnClickListener(myClickListener);
		rlApplyCertification.setOnClickListener(myClickListener);
		rlSystemMessages.setOnClickListener(myClickListener);

		supplierInfoShow.setLogoOnClick(this);
	}

	/**
	 * 打开页面时的加载显示
	 */
	private void beginShow() {
		try {
			Supplier supplier = SupIndexShared.getSupplier();
			Index index = SupIndexShared.getIndex();
			if (index != null
					&& index.getSupplier().getSupId() == keyCache.supId) {
				showIndexMessage(index);
			}
			if (supplier.getSupCount() != null
					&& !supplier.getSupCount().equals("")
					&& supplier.getSupPassword() != null
					&& !supplier.getSupPassword().equals("")) {
				supplierInfoShow.show(supplier);
				normalDataLoader.load();
			} else {
				EnvironmentUtil.errorLogin(SupIndexActivity.this);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 请求更新首页显示数据
	 */
	private void getIndexDataResult() {
		try {
			if (CheckStateUtil.check(gsonBean)) {
				Index index = DataUtil.gson.fromJson(gsonBean.getStrJson(),
						Index.class);
				showIndexMessage(index);
				SupIndexShared.saveSupplierIndex(index);
				supplierInfoShow.show(index.getSupplier());
			} else {
				// CommonUtil.errorLogin(SupIndexActivity.this);
			}
		} catch (Exception e) {
			e.printStackTrace();
			ToastUtil.show(getBaseContext(), "网络连接异常");
		}
	}

	private void showIndexMessage(Index index) {
		try {
			tvGoodsMessage.setText(index.getGoodsNumber() + "个商品");
			switch (index.getSupplier().getCerState()) {
			case DataState.DELETE:
				tvCertificationMessage.setText(index.getCerCompanyNumber()
						+ "家已认证");
				rlApplyCertification.setFocusable(true);
				break;
			case DataState.SUCCESS:
				tvCertificationMessage.setText("您已认证~");
				rlApplyCertification.setFocusable(false);
				break;
			case DataState.ADD:
				tvCertificationMessage.setText("等待审核中～");
				rlApplyCertification.setFocusable(false);
				break;
			case DataState.HAVE_BUT_DELETE:
				tvCertificationMessage.setText("认证未通过～");
				rlApplyCertification.setFocusable(true);
			default:
				break;
			}

			int messageNumber = index.getNewSystemMessageNum();
			if (messageNumber != 0) {
				tvSystemMessage.setBackgroundResource(R.drawable.yuan);
				if (messageNumber <= 9) {
					tvSystemMessage.setText(String.valueOf(messageNumber));
				} else {
					tvSystemMessage.setText("N");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 系统按键的设置
	 * *****************************************************************************************************************************************/

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_MORE;
			Intent intent = new Intent(getBaseContext(), CargoActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			this.finish();
			return false;
		}
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.exit:
			System.exit(0);
			this.finish();
			break;
		default:
			break;
		}
		return true;

	}

	/**
	 * 设置各控件的点击监听
	 */
	OnClickListener myClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Intent intent = null;

			switch (v.getId()) {

			case R.id.ivPublicTitleReturn:
				CargoActivity.OPEN_CHOOSE = MyStateUtil.OPEN_MORE;
				intent = new Intent(getBaseContext(), CargoActivity.class);
				startActivity(intent);
				break;

			case R.id.ivPublicTitleOther:
				intent = new Intent(getBaseContext(), SupSettingActivity.class);
				startActivity(intent);
				break;

			case R.id.tvSupIndexQuickAddButton:
				intent = new Intent(getBaseContext(), SupCameraActivity.class);
				SupCache.pictureList.clear();
				SupInputGoodsInfoActivity.TO_ADD_GOODS = true;
				SupCache.from = 0;
				startActivity(intent);
				break;

			case R.id.rlSupIndexGoodsManagement:
				intent = new Intent(getBaseContext(),
						SupGoodsManagerActivity.class);
				startActivity(intent);
				break;

			case R.id.rlSupIndexApplyCertification:
				if (!rlApplyCertification.isFocusable()) {
					return;
				}
				intent = new Intent(getBaseContext(),
						SupCertificationActivity.class);
				startActivity(intent);
				break;
			case R.id.rlSupIndexSystemMessages:
				intent = new Intent(getBaseContext(),
						SupSystemMessageListActivity.class);
				startActivity(intent);
				break;

			default:
				break;
			}
			SupIndexActivity.this.finish();

		}
	};

	@Override
	public void beforeLoad() {
		// TODO Auto-generated method stub

	}

	@Override
	public void toLoad(Message msg) throws Exception {
		// TODO Auto-generated method stub
		gsonBean = supplierIndexService.execute(keyCache.supId, keyCache.key);
		msg.what = MyStateUtil.INDEX_RESULT;
	}

	@Override
	public void afterLoad(int state) {
		// TODO Auto-generated method stub
		switch (state) {
		case MyStateUtil.INDEX_RESULT:
			getIndexDataResult();
			break;

		case MyStateUtil.RETURN_FAIL:
			ToastUtil.show(getBaseContext(), "无对应数据");
			break;
		case MyStateUtil.NOT_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "无网络连接");
			break;
		case MyStateUtil.ERROR_NET_CONNECTION:
			ToastUtil.show(getBaseContext(), "网络连接异常");
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode == RESULT_OK && requestCode == MyStateUtil.ALBUM_CODE) {
			ContentResolver resolver = getContentResolver();
			Uri originalUri = data.getData();
			try {

				Bitmap bitmap = MediaStore.Images.Media.getBitmap(resolver,
						originalUri);
				supplierInfoShow.setLogo(bitmap);
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

}
